import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { getSongDetail, getSongLyric } from '../service/player'
import { ILyric, parseLyric } from '@/utils/parse-lyric'

export const fetchCurrentSongAction = createAsyncThunk(
  'currentSong',
  (id: number, { dispatch }) => {
    // 1.获取歌曲信息
    getSongDetail(id).then((res) => {
      if (!res.songs.length) return
      const song = res.songs[0]
      dispatch(changeCurrentSongAction(song))
    })

    // 2.获取歌词数据
    getSongLyric(id).then((res) => {
      // 1.获取歌词的字符串
      const lyricString = res.lrc.lyric

      //2. 调用解析歌词的函数
      const lyric = parseLyric(lyricString)
      dispatch(changeLyricsAction(lyric))
    })
  }
)

interface IPlayerState {
  currentSong: any
  lyrics: ILyric[]
}

const initialState: IPlayerState = {
  currentSong: {
    name: '纯音乐演奏',
    id: 356538,
    pst: 0,
    t: 0,
    ar: [
      {
        id: 11704,
        name: '高旗&超载乐队',
        tns: [],
        alias: []
      }
    ],
    alia: [],
    pop: 25,
    st: 0,
    rt: '',
    fee: 0,
    v: 8,
    crbt: null,
    cf: '',
    al: {
      id: 35195,
      name: '超载 同名专辑',
      picUrl:
        'https://p2.music.126.net/ErJyVo4fjEST_yRM1pMZSQ==/109951164371936640.jpg',
      tns: [],
      pic_str: '109951164371936640',
      pic: 109951164371936640
    },
    dt: 116000,
    h: {
      br: 320000,
      fid: 0,
      size: 4681240,
      vd: -2,
      sr: 44100
    },
    m: {
      br: 192000,
      fid: 0,
      size: 2808782,
      vd: -2,
      sr: 44100
    },
    l: {
      br: 128000,
      fid: 0,
      size: 1872554,
      vd: 0,
      sr: 44100
    },
    sq: null,
    hr: null,
    a: null,
    cd: '1',
    no: 11,
    rtUrl: null,
    ftype: 0,
    rtUrls: [],
    djId: 0,
    copyright: 2,
    s_id: 0,
    mark: 131072,
    originCoverType: 0,
    originSongSimpleData: null,
    tagPicList: null,
    resourceState: true,
    version: 8,
    songJumpInfo: null,
    entertainmentTags: null,
    awardTags: null,
    single: 0,
    noCopyrightRcmd: null,
    mv: 0,
    rtype: 0,
    rurl: null,
    mst: 9,
    cp: 0,
    publishTime: 838828800000
  },
  lyrics: []
}

const playerSlice = createSlice({
  name: 'player',
  initialState,
  reducers: {
    changeCurrentSongAction(state, { payload }) {
      state.currentSong = payload
    },
    changeLyricsAction(state, { payload }) {
      state.lyrics = payload
    }
  }
})

export const { changeCurrentSongAction, changeLyricsAction } =
  playerSlice.actions
export default playerSlice.reducer
